<template>
  <div class="asset-ledger-container">
    <h2>资产台账</h2>
    
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="资产编号">
          <el-input v-model="searchForm.assetCode" placeholder="请输入资产编号"></el-input>
        </el-form-item>
        <el-form-item label="资产名称">
          <el-input v-model="searchForm.assetName" placeholder="请输入资产名称"></el-input>
        </el-form-item>
        <el-form-item label="资产状态">
          <el-select v-model="searchForm.status" placeholder="选择状态">
            <el-option label="在用" value="在用"></el-option>
            <el-option label="闲置" value="闲置"></el-option>
            <el-option label="报废" value="报废"></el-option>
            <el-option label="借出" value="借出"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用部门">
          <el-select v-model="searchForm.deptId" placeholder="选择部门">
            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购日期">
          <el-date-picker
            v-model="searchForm.purchaseDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button type="success" @click="exportLedger">导出台账</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <div class="table-controls">
        <el-checkbox-group v-model="selectedColumns" @change="updateTableColumns">
          <el-checkbox-button v-for="col in allColumns" :key="col.prop" :label="col.prop">{{ col.label }}</el-checkbox-button>
        </el-checkbox-group>
      </div>
      
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label" :width="col.width" :align="col.align">
          <template v-if="col.prop === 'status'" #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'purchaseDate' || col.prop === 'createTime'" #default="scope">
            {{ formatDate(scope.row[col.prop]) }}
          </template>
          <template v-else-if="col.prop === 'originalValue' || col.prop === 'currentValue'" #default="scope">
            {{ formatCurrency(scope.row[col.prop]) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 资产详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="资产详情" width="60%">
      <div class="detail-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <span class="detail-label">资产编号：</span>
              <span class="detail-value">{{ currentAsset.assetCode }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">资产名称：</span>
              <span class="detail-value">{{ currentAsset.assetName }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">资产类别：</span>
              <span class="detail-value">{{ currentAsset.categoryName }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">规格型号：</span>
              <span class="detail-value">{{ currentAsset.specification }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">制造商：</span>
              <span class="detail-value">{{ currentAsset.manufacturer }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <span class="detail-label">资产状态：</span>
              <el-tag :type="getStatusTagType(currentAsset.status)">{{ currentAsset.status }}</el-tag>
            </div>
            <div class="detail-item">
              <span class="detail-label">使用部门：</span>
              <span class="detail-value">{{ currentAsset.deptName }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">使用人：</span>
              <span class="detail-value">{{ currentAsset.userName }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">原值：</span>
              <span class="detail-value">{{ formatCurrency(currentAsset.originalValue) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">净值：</span>
              <span class="detail-value">{{ formatCurrency(currentAsset.currentValue) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div class="detail-item">
          <span class="detail-label">存放地点：</span>
          <span class="detail-value">{{ currentAsset.location }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">采购日期：</span>
          <span class="detail-value">{{ formatDate(currentAsset.purchaseDate) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">启用日期：</span>
          <span class="detail-value">{{ formatDate(currentAsset.enableDate) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">备注：</span>
          <span class="detail-value">{{ currentAsset.remark }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'AssetLedger',
  setup() {
    const searchForm = ref({
      assetCode: '',
      assetName: '',
      status: '',
      deptId: '',
      purchaseDate: ''
    })
    
    const deptList = ref([
      { id: '1', name: '技术部' },
      { id: '2', name: '财务部' },
      { id: '3', name: '人力资源部' },
      { id: '4', name: '市场部' },
      { id: '5', name: '行政部' }
    ])
    
    const tableData = ref([])
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const selectedColumns = ref(['assetCode', 'assetName', 'categoryName', 'status', 'deptName', 'userName', 'originalValue'])
    const allColumns = ref([
      { prop: 'assetCode', label: '资产编号', width: 150 },
      { prop: 'assetName', label: '资产名称', width: 180 },
      { prop: 'categoryName', label: '资产类别', width: 120 },
      { prop: 'status', label: '状态', width: 80, align: 'center' },
      { prop: 'deptName', label: '使用部门', width: 120 },
      { prop: 'userName', label: '使用人', width: 100 },
      { prop: 'originalValue', label: '原值(元)', width: 100, align: 'right' },
      { prop: 'currentValue', label: '净值(元)', width: 100, align: 'right' },
      { prop: 'purchaseDate', label: '采购日期', width: 120 },
      { prop: 'manufacturer', label: '制造商', width: 120 },
      { prop: 'specification', label: '规格型号', width: 150 },
      { prop: 'location', label: '存放地点', width: 150 },
      { prop: 'createTime', label: '创建时间', width: 150 }
    ])
    
    const detailDialogVisible = ref(false)
    const currentAsset = ref({})
    const multipleSelection = ref([])
    
    // 计算可见列
    const visibleColumns = computed(() => {
      return allColumns.value.filter(col => selectedColumns.value.includes(col.prop))
    })
    
    // 获取资产台账数据
    const getAssetLedger = async () => {
      try {
        const params = {
          ...searchForm.value,
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize
        }
        
        const response = await axios.get('/api/statistics/assets', {
          params
        })
        
        if (response.code === 200 && response.data) {
          tableData.value = response.data.records || response.data
          pagination.value.total = response.data.total || 0
        } else {
          // 使用模拟数据
          setMockData()
        }
      } catch (error) {
        console.error('获取资产台账数据失败:', error)
        setMockData()
      }
    }
    
    // 设置模拟数据
    const setMockData = () => {
      tableData.value = [
        {
          id: '1',
          assetCode: 'ZC2024001',
          assetName: '联想ThinkPad笔记本电脑',
          categoryName: '电子设备',
          specification: 'ThinkPad T14',
          manufacturer: '联想',
          status: '在用',
          deptName: '技术部',
          userName: '张三',
          location: 'A栋301室',
          originalValue: 8999,
          currentValue: 7500,
          purchaseDate: '2024-01-15',
          enableDate: '2024-01-20',
          createTime: '2024-01-15 10:30:00',
          remark: '办公用'
        },
        {
          id: '2',
          assetCode: 'ZC2024002',
          assetName: 'Dell显示器',
          categoryName: '电子设备',
          specification: 'Dell U2720Q',
          manufacturer: 'Dell',
          status: '在用',
          deptName: '技术部',
          userName: '李四',
          location: 'A栋301室',
          originalValue: 3499,
          currentValue: 3000,
          purchaseDate: '2024-02-20',
          enableDate: '2024-02-22',
          createTime: '2024-02-20 14:20:00',
          remark: '高清显示器'
        },
        {
          id: '3',
          assetCode: 'ZC2024003',
          assetName: 'HP激光打印机',
          categoryName: '办公设备',
          specification: 'HP LaserJet Pro',
          manufacturer: 'HP',
          status: '闲置',
          deptName: '行政部',
          userName: '',
          location: 'B栋101室',
          originalValue: 2499,
          currentValue: 2000,
          purchaseDate: '2023-11-10',
          enableDate: '2023-11-15',
          createTime: '2023-11-10 09:15:00',
          remark: '备用打印机'
        },
        {
          id: '4',
          assetCode: 'ZC2024004',
          assetName: '办公桌椅套装',
          categoryName: '办公家具',
          specification: '标准型',
          manufacturer: '震旦家具',
          status: '在用',
          deptName: '人力资源部',
          userName: '王五',
          location: 'C栋201室',
          originalValue: 1500,
          currentValue: 1200,
          purchaseDate: '2024-03-05',
          enableDate: '2024-03-06',
          createTime: '2024-03-05 11:00:00',
          remark: ''
        },
        {
          id: '5',
          assetCode: 'ZC2024005',
          assetName: '财务软件',
          categoryName: '无形资产',
          specification: '企业版',
          manufacturer: '金蝶',
          status: '在用',
          deptName: '财务部',
          userName: '赵六',
          location: '服务器',
          originalValue: 50000,
          currentValue: 45000,
          purchaseDate: '2023-12-01',
          enableDate: '2023-12-05',
          createTime: '2023-12-01 16:30:00',
          remark: '财务系统'
        }
      ]
      pagination.value.total = 100 // 模拟总数
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const statusMap = {
        '在用': 'success',
        '闲置': 'warning',
        '报废': 'danger',
        '借出': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      if (isNaN(date.getTime())) return dateStr
      return date.toLocaleDateString('zh-CN')
    }
    
    // 格式化货币
    const formatCurrency = (value) => {
      if (!value && value !== 0) return ''
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    }
    
    // 查询
    const search = () => {
      pagination.value.currentPage = 1
      getAssetLedger()
    }
    
    // 重置
    const reset = () => {
      searchForm.value = {
        assetCode: '',
        assetName: '',
        status: '',
        deptId: '',
        purchaseDate: ''
      }
      pagination.value.currentPage = 1
      getAssetLedger()
    }
    
    // 导出台账
    const exportLedger = () => {
      // 实际项目中这里可以调用后端导出接口
      console.log('导出资产台账')
      alert('资产台账导出成功')
    }
    
    // 更新表格列
    const updateTableColumns = () => {
      // 列的显示/隐藏由computed自动处理
    }
    
    // 查看详情
    const viewDetail = (row) => {
      currentAsset.value = { ...row }
      detailDialogVisible.value = true
    }
    
    // 处理选中项变化
    const handleSelectionChange = (val) => {
      multipleSelection.value = val
    }
    
    // 处理页码大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      getAssetLedger()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      getAssetLedger()
    }
    
    onMounted(() => {
      getAssetLedger()
    })
    
    return {
      searchForm,
      deptList,
      tableData,
      pagination,
      selectedColumns,
      allColumns,
      visibleColumns,
      detailDialogVisible,
      currentAsset,
      multipleSelection,
      getStatusTagType,
      formatDate,
      formatCurrency,
      search,
      reset,
      exportLedger,
      updateTableColumns,
      viewDetail,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.asset-ledger-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 20px;
  margin-right: 20px;
}

.table-card {
  margin-top: 20px;
}

.table-controls {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.detail-content {
  padding: 10px 0;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}

.detail-label {
  width: 100px;
  font-weight: bold;
  color: #606266;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
}
</style>